package Server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

public class MailboxChecker extends Thread {
	private ChatRooms cr;
	private String room;

	public MailboxChecker(String room, ChatRooms cr) {
		this.cr = cr;

		this.room = room;
	}

	public void run() {
		boolean empty = false;
		OutputStream os = null;
		boolean shallRun = true;
		while (shallRun && !empty) {

			String message = cr.getMailbox(room).removeMessage();
			if (!message.equals("IsToBeRemoved")) {
				message += "\n";
				if (!message.equals("")) {
					Vector<Socket> participants = cr.getParticipants(room);
					if (participants.size() != 0) {
						for (Socket s : participants) {
							try {
								os = s.getOutputStream();
								os.write(message.getBytes());
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					} else {
						empty = true;
					}
				}

			} else {
				shallRun = false;
			}
		}
	}

}